package cn.wolfcode.crm.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Notice;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.RequiredPermission;
import cn.wolfcode.crm.util.SendMultEmail;

@Controller
@RequestMapping("/notice")
public class NoticeController {
	@Autowired
	private IDepartmentService departmentService;
	
	@Autowired
	private IEmployeeService employeeService;
	
	@RequiredPermission({"发布通知界面", "notice:list"})
	@RequestMapping("/list")
	public String list(@ModelAttribute("qo") QueryObject qo, Model model) {
		List<Department> list = departmentService.selectAll(qo);
		model.addAttribute("departments", list);
		System.out.println("come here ---------");
		return "notice/list";
	}
	
	@RequiredPermission({"发布通知发送", "notice:publish"})
	@RequestMapping("/publish")
	public String publish(Notice notice, Model model) {
//		List<Department> list = departmentService.selectAll(qo);
//		model.addAttribute("departments", list);
		
		//判断是否为全员工发送
		if(notice.getDepartmentId() == -1)
			notice.setDepartmentId(null);
		
		//获取对应部门的员工
		List<Employee> list = employeeService.selectByDeptId(notice.getDepartmentId());
		
		//存储邮件地址
		List<String> address = new ArrayList<String>();
		try {
			for(int i = 0; i<list.size(); i++) {
				address.add(list.get(i).getEmail());
			}
			SendMultEmail send = new SendMultEmail();
			send.setAddress(address);
			send.setInfo(notice.getContent());
			send.start();
			System.out.println("succeed send email to employee-----");
			String str = "succeed send email to employee";
			model.addAttribute("sendResult", str);
			return "redirect:/notice/list.do";
		}catch(Exception e) {
			e.printStackTrace();
			String str = "failed send email to employee";
			model.addAttribute("sendResult", str);
			return "redirect:/notice/list.do";
		}
		
	}
}
